var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var less = require('gulp-less');
var sourcemaps = require('gulp-sourcemaps');
var watchPath = require('gulp-watch-path');
var sourcemaps = require('gulp-sourcemaps');
var cssmin = require('gulp-cssmin');
var ext_replace = require('gulp-ext-replace');
var autoprefixer = require('gulp-autoprefixer');
var combiner = require('stream-combiner2');

var paths = {
  scripts: 'static/js/**/*.js',
  images: 'static/img/**/*',
  less: 'static/less/**/*.less',
  css: ['dist/css/*.css', '!dist/css/*.min.css'],
};

var handleError = function (err) {
  console.log(err);
};

gulp.task('scripts', function() {
  return gulp.src(paths.scripts)
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'));
});

gulp.task('watchscripts', function() {
  gulp.watch(paths.scripts, function(event) {
    var wpaths = watchPath(event, 'static/js/', 'dist/js/');
    console.log(wpaths);
    // donot end gulp when err
    var combined = combiner.obj([
      gulp.src(wpaths.srcPath),
      sourcemaps.init(),
      uglify(),
      sourcemaps.write('./'),
      gulp.dest(wpaths.distDir)
    ]);
    combined.on('error', handleError);
  });
});

gulp.task('less', function() {
  return gulp.src(paths.less)
    .pipe(less())
    .pipe(autoprefixer())
    .pipe(gulp.dest('dist/css'));
});

gulp.task('cssmin', ['less'], function() {
  return gulp.src(paths.css)
    .pipe(cssmin())
    .pipe(ext_replace('.min.css'))
    .pipe(gulp.dest('dist/css'));
});

gulp.task('watchless', function() {
  gulp.watch('static/less/**/*.less', function(event) {
    var wpaths = watchPath(event, 'static/less/', 'dist/css');
    console.log(wpaths);
    var combined = combiner.obj([
      gulp.src(wpaths.srcPath),
      less(),
      autoprefixer(),
      cssmin(),
      ext_replace('min.css'),
      gulp.dest(wpaths.distDir)
    ]);
    combined.on('error', handleError);
  });
});

gulp.task('images', function() {
  return gulp.src(paths.images)
    .pipe(imagemin({optimizationLevel: 5}))
    .pipe(gulp.dest('dist/img'));
});

gulp.task('watchimages', function() {
  gulp.watch(paths.images, function(event) {
    var wpaths = watchPath(event, 'static/img/', 'dist/img/');
    console.log(wpaths);
    var combined = combiner.obj([
      gulp.src(wpaths.srcPath),
      imagemin({optimizationLevel: 5}),
      gulp.dest(wpaths.distDir)
    ]);
    combined.on('error', handleError);
  });
});


// 开发环境，监控文件修改，自动处理, 注意：提交代码时需使用线上环境的
gulp.task('watch', ['watchscripts', 'watchless', 'watchimages']);
// 线上环境，运行全部任务
gulp.task('default', ['scripts', 'images', 'cssmin']);
